package com.netx.generics.basic;
import com.netx.generics.translation.Results;
import com.netx.generics.translation.TranslationStep;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class ContextRulesApplyer extends TranslationStep {

	private final Map<String,ContextRules> _rules;
	
	public ContextRulesApplyer(ContextAnalyzer analyzer, Map<String,ContextRules> rules) {
		super(analyzer);
		Checker.checkNull(rules, "rules");
		_rules = rules;
	}

	public Object performWork(Results r) {
		Context root = (Context)r.getContents();
		Set<Entry<String,ContextRules>> entries = _rules.entrySet();
		for(Entry<String,ContextRules> entry : entries) {
			if(!entry.getKey().startsWith("root")) {
				addError(r, entry.getKey(), "invalid context name; context must be identified starting in 'root'");
			}
			else {
				Context ctx = null;
				if(entry.getKey().equals("root")) {
					ctx = root;
				}
				else {
					ctx = root.getContext(entry.getKey().substring(5));
				}
				if(ctx == null) {
					addError(r, entry.getKey(), "context not found");
				}
				else {
					try {
						ctx.applyRules(entry.getValue());
					}
					catch(RulesException re) {
						r.addMessages("in '"+entry.getKey()+"': ", null, re.getContents());
					}
				}
			}
		}
		return root;
	}
}
